###Clear R--------------------
rm(list=ls())

###Function to recode variables to range from lowest (0) to highest (1) observation---------------------
zero1 <- function(x, minx=NA, maxx=NA){
  res <- NA
  if(is.na(minx)) res <- (x - min(x,na.rm=T))/(max(x,na.rm=T) -min(x,na.rm=T))
  if(!is.na(minx)) res <- (x - minx)/(maxx -minx)
  res
}

####function to install packages if they don't exist----------------
ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg)) 
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

# usage
packages <- c("psych", "ggplot2", "interplot", "MASS", "foreign",  "car", "stringr", "stargazer", "xtable", "moments", "dplyr", "lavaan", "interplot")
ipak(packages)

#load data
load("Study6_data.RData")

### Figure 1: effects of cues of the range of partisan social identity strength------------
model1 <- lm(supportttip~identitystrength*ownside, data=data)
out <- interplot(m=model1, var1='ownside',var2='identitystrength')
forplot <- out$data
ggplot(forplot,aes(x=fake,y=coef1))+geom_ribbon(aes(ymin=lb,ymax=ub),alpha=.2)+theme_bw()+geom_line()+xlab("Partisan Social Identity Strength")+ylab("Support for Policy")+ geom_abline(intercept=0,slope=0,lty=2)
ggsave("Study6_DK_idinteraction.pdf",width=8,height=6)

#### Figure 2: Denmark: Marginal Effect of Cues across Levels of Party Identity and CRT

## CRT at 0 or -1SD
m0 <- lm(supportttip~inparty*scale(CRTall,center=mean(CRTall)-sd(CRTall),scale=F)*identitystrength,data)
summary(m0)
m_0 <- interplot(m0,var1 = "inparty",var2='identitystrength')
m_0$data$CRT='-1 SD'

## CRT at mean
m1 <- lm(supportttip~inparty*scale(CRTall,center=mean(CRTall,na.rm=T),scale=F)*identitystrength,data)
summary(m1)
m_1 <- interplot(m1,var1 = "inparty",var2='identitystrength')
m_1$data$CRT='Mean'

## CRT at +1
m2 <- lm(supportttip~inparty*scale(CRTall,center=mean(CRTall)+sd(CRTall),scale=F)*identitystrength,data)
summary(m2)
m_2 <- interplot(m2,var1 = "inparty",var2='identitystrength')
m_2$data$CRT='+1 SD'

forplot <- rbind(m_0$data,m_1$data,m_2$data)
forplot$battery      <- c("CRT")
forplot$CRT <- factor(forplot$CRT,levels = c("-1 SD","Mean","+1 SD"))
ggplot(forplot,aes(x=fake,y=coef1))+geom_line()+facet_grid(.~CRT)+xlab("Party ID Strength")+theme_bw()+ylab("Marginal effect of In-party Cue on Policy Support ")+geom_ribbon(aes(ymin=lb,ymax=ub),alpha=.5)+geom_hline(yintercept = 0,lty="dashed")+scale_fill_manual(values=c("dark green"))+scale_colour_manual(values=c("black"))

ggsave("Study6_DK_CRT.pdf",width=8,height=6)

